package com.example.demo.controller;

import javax.servlet.http.HttpServletRequest;


import javax.servlet.http.HttpSession;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.example.demo.entity.Food;
import com.example.demo.entity.FoodType;
import com.example.demo.service.FoodType_Service;
import com.example.demo.service.Food_Service;

@RequestMapping("FoodType")
@RestController
public class FoodType_Controller extends Basic_Controller<FoodType>{
	@Autowired
	FoodType_Service service;
	@Autowired
	Food_Service foodservice;
	
	@RequestMapping("test")
	@ResponseBody
	public FoodType test(FoodType u) {
		return u;
	}
	@RequestMapping("insertall")
	public void insertall() throws Exception {
		Connection conn=Jsoup.connect("https://home.meishichina.com/recipe/recai/");
		Document doc=conn.get();
//		System.out.println(doc.html());
		Elements els=doc.select(".nav_wrap2 li");
		for(int i=1;i<7;i++) {
			Element el=els.get(i);
			FoodType type= new FoodType();
			type.setName(el.selectFirst("a").text());
            service.insert(type);   //类别名称   添加类型，获取id
			int typeid=type.getId();//获得商品类型对应的id
	        String url=el.selectFirst("a").attr("href");
			getpage(url,1,4,typeid);
		}
		
	}
	public  void getpage(String url,int page,int max,int typeid)throws Exception {
		Connection conn=Jsoup.connect(url+"/page/"+page+"/");
		Document doc=conn.get();
		Elements els=doc.select(".ui_newlist_1  li");
		for(int i=1;i<els.size();i++) {
			Element el=els.get(i);
			Food food=new Food();
			food.setFoodtype_id(typeid);
        	String name=el.selectFirst(".detail h2 a").text();
			food.setName(name);
			String picurl= el.selectFirst(".pic img").attr("data-src");
			food.setPicurl(picurl);
			food.setPrice(0);
			food.setStatus(0);
			foodservice.insert(food);
			
	        //System.out.println(el.selectFirst(".pic img").attr("data-src"));//picurl
			//System.out.println(el.selectFirst(".detail h2 a").text());//name
			//添加菜  
		}
		if(page<max)
		getpage(url,++page,max,typeid);
		
	}

	
}
